//
//  BDForgetPasswordViewController.m
//  BadBoy
//
//  Created by wen on 2017/3/30.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDForgetPasswordViewController.h"
#import "BDUserModel.h"
@interface BDForgetPasswordViewController ()
{
    BOOL clickGetButton;
    UIColor *finishColor;
}

@property (nonatomic, strong) UIButton *getButton;
@property (nonatomic, strong) UITextField *nePassField;
@property (nonatomic, strong) UITextField *supassField;
@property (nonatomic, strong) UITextField *userField;
@property (nonatomic, strong) UITextField *codeField;
@property (nonatomic, strong) UIButton *loginButton;

@end

@implementation BDForgetPasswordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([self.type isEqualToString:ASLocalizedString(@"修改密码")]) {
        self.title = ASLocalizedString(@"重置密码");
        self.nePassField.keyboardType = UIKeyboardTypeDefault;
        self.supassField.keyboardType = UIKeyboardTypeDefault;
        self.userField.keyboardType = UIKeyboardTypeNumberPad;
        self.codeField.keyboardType = UIKeyboardTypeNumberPad;
        _nePassField.placeholder = ASLocalizedString(@"6-16个字符");
        _supassField.placeholder = ASLocalizedString(@"6-16个字符");
    }else{
        self.title = ASLocalizedString(@"设置支付密码");
        self.nePassField.keyboardType = UIKeyboardTypeNumberPad;
        self.supassField.keyboardType = UIKeyboardTypeNumberPad;
        self.userField.keyboardType = UIKeyboardTypeNumberPad;
        self.codeField.keyboardType = UIKeyboardTypeNumberPad;
        _nePassField.placeholder = ASLocalizedString(@"6位数字密码");
        _supassField.placeholder = ASLocalizedString(@"6位数字密码");
        [_nePassField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
         [_supassField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    
    [self bindRAC];
}

- (void)bindRAC{
    [[self.loginButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        NSString *alert = nil;
        if ([self.type isEqualToString:ASLocalizedString(@"修改密码")]){
        if (!(self.nePassField.text.length >= 6 && self.nePassField.text.length <= 16)) {
            alert = ASLocalizedString(@"新密码格式错误，请重新填写");
        }
        else if (!(self.supassField.text.length >= 6 && self.supassField.text.length <= 16)) {
            alert = ASLocalizedString(@"确认密码格式错误，请重新填写");
        }
        else if (![self.nePassField.text isEqualToString:self.supassField.text]) {
            alert = ASLocalizedString(@"两次密码输入不一致，请重新填写");
        }
        else if (self.userField.text.length != 11) {
            alert = ASLocalizedString(@"请填写合法的手机号");
        }
        else if (self.codeField.text.length == 0) {
            alert = ASLocalizedString(@"请填写验证码");
        }else if (self.codeField.text.length != 4) {
            alert = ASLocalizedString(@"验证码错误，请重新填写");
        }
        }else{
            if (!(self.nePassField.text.length == 6)) {
                alert = ASLocalizedString(@"新密码格式错误，请重新填写");
            }
            else if (!(self.supassField.text.length == 6)) {
                alert = ASLocalizedString(@"确认密码格式错误，请重新填写");
            }
            else if (![self.nePassField.text isEqualToString:self.supassField.text]) {
                alert = ASLocalizedString(@"两次密码输入不一致，请重新填写");
            }
            else if (self.userField.text.length != 11) {
                alert = ASLocalizedString(@"请填写合法的手机号");
            }
            else if (self.codeField.text.length == 0) {
                alert = ASLocalizedString(@"请填写验证码");
            }else if (self.codeField.text.length != 4) {
                alert = ASLocalizedString(@"验证码错误，请重新填写");
            }
        }
        if (alert != nil) {
            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:alert clickHidden:NO clickBlock:nil];
            return;
        }
        
        NSString *url = [self.type isEqualToString:ASLocalizedString(@"修改密码")]?[NSString stringWithFormat:@"%@user/password", KBDBaseURL]:[NSString stringWithFormat:@"%@users/paymentPassword", KBDBaseURL];

        NSString *validation = [self.type isEqualToString:ASLocalizedString(@"修改密码")]?nil:[BDUserModel getHeaderValidation];
        
        NSDictionary *para = @{@"mobile":self.userField.text,
                               @"code":self.codeField.text,
                               @"password":self.nePassField.text,
                               @"re_password":self.supassField.text};
        
        [MBManager showLoadingAlert:ASLocalizedString(@"请稍等")clickHidden:NO clickBlock:nil];
        RACCommand *command = [BDNetworkingServer yy_PUT:url parameters:para validation:validation automaticProcessingError:NO];
        RACSignal *signal = [command execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
//            [MBManager hideAlert];
            [MBManager showBriefAlert:ASLocalizedString(@"重置密码成功")clickHidden:YES clickBlock:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }];
        
        [signal subscribeError:^(NSError * _Nullable error) {
            
            NSString *alert = ASLocalizedString(@"新密码格式错误或验证码错误");
            if (error.code == 40002) {
                alert = ASLocalizedString(@"验证码错误或失效");
            }else if (error.code == 40001){
                alert = ASLocalizedString(@"手机号码与当前用户不一样");
            }
            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:alert clickHidden:NO clickBlock:nil];
        }];
    }];
    
    RACSignal *getEnable =[RACSignal combineLatest:@[self.userField.rac_textSignal] reduce:^id _Nullable{
        return @(self.userField.text.length == 11);
    }];
    RAC(self.getButton, userInteractionEnabled) = getEnable;
    [getEnable subscribeNext:^(id  _Nullable x) {
        if (clickGetButton == NO) {
            self.getButton.backgroundColor = [x boolValue] ? kCodeButtonColor : kNOValidColor;
            // BDLog(ASLocalizedString(@"获取验证码按钮是否能按：%d"), self.getButton.userInteractionEnabled);
        }else{
            finishColor = [x boolValue] ? kCodeButtonColor : kNOValidColor;
        }
    }];
    
    RACSignal *getSendSignal = [self.getButton rac_signalForControlEvents:UIControlEventTouchUpInside];
    [getSendSignal subscribeNext:^(id  _Nullable x) {
        // BDLog(ASLocalizedString(@"点击了发送验证的按钮"));
        clickGetButton = YES;
        self.getButton.backgroundColor = kNOValidColor;
        _getButton.userInteractionEnabled = NO;
        
        NSDictionary *para = @{@"mobile":self.userField.text};
        NSString *url = [NSString stringWithFormat:@"%@sms", KBDBaseURL];
        
        RACCommand *getCodeCommand = [BDNetworkingServer yy_POST:url parameters:para validation:nil automaticProcessingError:NO];
        RACSignal *getCodeSignal = [getCodeCommand execute:nil];
        
        [[getCodeSignal deliverOn:[RACScheduler mainThreadScheduler]] subscribeNext:^(id  _Nullable x) {
            [self.codeField becomeFirstResponder];
            
            @weakify(self);
            __block NSInteger number = 60;
            NSInteger numberLimit = number;
            RACSignal *timeSignal = [[[[[RACSignal interval:1.0f onScheduler:[RACScheduler mainThreadScheduler]] take:numberLimit] startWith:[NSDate date]] map:^id(NSDate *date) {
                @strongify(self);
                if (number == 0) {
                    [self.getButton setTitle:ASLocalizedString(@"重新发送")forState:UIControlStateNormal];
                    self.getButton.userInteractionEnabled = YES;
                    clickGetButton = NO;
                    self.getButton.backgroundColor = finishColor == nil ? kCodeButtonColor : finishColor;
                    return @YES;
                }else{
                    [self.getButton setTitle:[NSString stringWithFormat:ASLocalizedString(@"剩余%ld秒"), number] forState:UIControlStateNormal];
                    //                    // BDLog(ASLocalizedString(@"按钮文本是什么：%@"), [NSString stringWithFormat:ASLocalizedString(@"剩余%ld秒"), number]);
                    number--;
                    return @NO;
                }
            }] takeUntil:self.rac_willDeallocSignal];
            
            _getButton.rac_command = [[RACCommand alloc]initWithEnabled:timeSignal signalBlock:^RACSignal *(id input) {
                number = numberLimit;
                return timeSignal;
            }];
        }];
        
        [getSendSignal subscribeError:^(NSError * _Nullable error) {
            [MBManager showCustomView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"error"]] title:ASLocalizedString(@"发送验证码失败，请稍后再试")clickHidden:NO clickBlock:nil];
            [self.getButton setTitle:ASLocalizedString(@"重新发送")forState:UIControlStateNormal];
            self.getButton.userInteractionEnabled = YES;
            clickGetButton = NO;
            self.getButton.backgroundColor = finishColor == nil ? kCodeButtonColor : finishColor;
        }];
    }];
}

- (UITextField *)nePassField{
    if (!_nePassField) {
        UIView *bkView = [[UIView alloc] initWithFrame:CGRectMake(0, kBDTopHeight + 10, kBDScreenWidth, 45)];
        bkView.backgroundColor = [UIColor whiteColor];
        bkView.layer.borderWidth = 0.5;
        bkView.layer.borderColor = kBDColorGray.CGColor;
        [self.view addSubview:bkView];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 90, 40)];
        titleLabel.font = [UIFont systemFontOfSize:15];
        titleLabel.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
        titleLabel.text = ASLocalizedString(@"新的密码");
        titleLabel.centerY = bkView.height / 2.0;
        [bkView addSubview:titleLabel];
        
        self.nePassField = [[UITextField alloc] initWithFrame:CGRectMake(100, 0, self.view.bounds.size.width - 40, 45)];
        _nePassField.font = [UIFont systemFontOfSize:14];
        _nePassField.tintColor = [UIColor lightGrayColor];
        _nePassField.borderStyle = UITextBorderStyleNone;
        _nePassField.secureTextEntry = YES;
        [bkView addSubview:_nePassField];
    }
    return _nePassField;
}

- (UITextField *)supassField{
    if (!_supassField) {
        UIView *bkView = [[UIView alloc] initWithFrame:CGRectMake(0, kBDTopHeight + 10 + 45, self.view.bounds.size.width, 45)];
        bkView.backgroundColor = [UIColor whiteColor];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.5)];
        line.backgroundColor = kBDColorGray;
        line.bottom = bkView.height;
        [bkView addSubview:line];
        
        [self.view addSubview:bkView];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 90, 40)];
        titleLabel.font = [UIFont systemFontOfSize:15];
        titleLabel.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
        titleLabel.text = ASLocalizedString(@"确认密码");
        titleLabel.centerY = bkView.height / 2.0;
        [bkView addSubview:titleLabel];
        
        self.supassField = [[UITextField alloc] initWithFrame:CGRectMake(100, 0, self.view.bounds.size.width - 40, 45)];
        _supassField.font = [UIFont systemFontOfSize:14];
        _supassField.tintColor = [UIColor lightGrayColor];
        _supassField.borderStyle = UITextBorderStyleNone;
        _supassField.secureTextEntry = YES;
        [bkView addSubview:_supassField];
    }
    return _supassField;
}

- (UITextField *)userField{
    if (!_userField) {
        UIView *bkView = [[UIView alloc] initWithFrame:CGRectMake(0, kBDTopHeight + 10 + 45 * 2, self.view.bounds.size.width, 45)];
        bkView.backgroundColor = [UIColor whiteColor];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.5)];
        line.backgroundColor = kBDColorGray;
        line.bottom = bkView.height;
        [bkView addSubview:line];
        
        [self.view addSubview:bkView];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 90, 40)];
        titleLabel.font = [UIFont systemFontOfSize:15];
        titleLabel.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
        titleLabel.text = ASLocalizedString(@"手机号码");
        titleLabel.centerY = bkView.height / 2.0;
        [bkView addSubview:titleLabel];
        
        self.getButton.right = self.view.width - 10;
        self.getButton.centerY = bkView.height / 2.0;
        [bkView addSubview:_getButton];
        
        self.userField = [[UITextField alloc] initWithFrame:CGRectMake(100, 0, self.getButton.left - 100, 45)];
        _userField.font = [UIFont systemFontOfSize:14];
        _userField.tintColor = [UIColor lightGrayColor];
        _userField.keyboardType = UIKeyboardTypeNumberPad;
        [bkView addSubview:_userField];
    }
    return _userField;
}

- (UIButton *)getButton{
    if (!_getButton) {
        self.getButton = [UIButton buttonWithType:UIButtonTypeCustom];
        NSString *title = ASLocalizedString(@"获取验证码");
        [_getButton setTitle:title forState:UIControlStateNormal];
        _getButton.backgroundColor = kNOValidColor;
        _getButton.titleLabel.font = [UIFont systemFontOfSize:14];
        _getButton.width = 90;
        _getButton.height = 35;
        _getButton.titleLabel.textAlignment = NSTextAlignmentCenter;
        _getButton.layer.masksToBounds = YES;
        _getButton.layer.cornerRadius = 4;
    }
    return _getButton;
}

- (UITextField *)codeField{
    if (!_codeField) {
        UIView *bkView = [[UIView alloc] initWithFrame:CGRectMake(0, kBDTopHeight + 10 + 45 * 3, self.view.bounds.size.width, 45)];
        bkView.backgroundColor = [UIColor whiteColor];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.5)];
        line.backgroundColor = kBDColorGray;
        line.bottom = bkView.height;
        [bkView addSubview:line];
        
        [self.view addSubview:bkView];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 90, 40)];
        titleLabel.font = [UIFont systemFontOfSize:15];
        titleLabel.textColor = [UIColor colorWithHexString:@"#4c4c4c"];
        titleLabel.text = ASLocalizedString(@"验证码");
        titleLabel.centerY = bkView.height / 2.0;
        [bkView addSubview:titleLabel];
        
        self.codeField = [[UITextField alloc] initWithFrame:CGRectMake(100, 0, self.view.bounds.size.width - 40, 45)];
        _codeField.font = [UIFont systemFontOfSize:14];
        _codeField.tintColor = [UIColor lightGrayColor];
        _codeField.borderStyle = UITextBorderStyleNone;
        _codeField.keyboardType = UIKeyboardTypeNumberPad;
        [bkView addSubview:_codeField];
    }
    return _codeField;
}

- (UIButton *)loginButton{
    if (!_loginButton) {
        self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _loginButton.frame = CGRectMake(10, kBDTopHeight + 10 + 45 * 4 + 20, self.view.bounds.size.width - 20, 45);
        [_loginButton setTitle:ASLocalizedString(@"确定")forState:UIControlStateNormal];
        [_loginButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _loginButton.backgroundColor = kLoginButtonColor;
        _loginButton.titleLabel.font = [UIFont systemFontOfSize:17];
        _loginButton.layer.masksToBounds = YES;
        _loginButton.layer.cornerRadius = 4;
        [self.view addSubview:_loginButton];
    }
    return _loginButton;
}

- (void)textFieldDidChange:(UITextField *)textField
{
    if (textField == self.nePassField || textField == self.supassField) {
        if (textField.text.length > 6) {
            textField.text = [textField.text substringToIndex:6];
            [MBManager showBriefAlert:ASLocalizedString(@"已经输入6位数字")clickHidden:YES clickBlock:nil];
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
